package com.bolins.examples.subspringside.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 可行性测试
 * 
 * @author liuys
 *
 */
@SuppressWarnings("serial")
public class TestSourcesPathServlet extends HttpServlet {
	private final static Logger logger = LoggerFactory.getLogger(TestSourcesPathServlet.class);
	private final static String SOURCES_BASE_PATH = "sourcesBasePath";
	private final static String BATH_PATH = "/sources";

	private String basePath;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		File root = new File(basePath);
		logger.info("Root file exists? : {}", root.exists());
		StringBuffer buf = new StringBuffer();
		showChildFile(root, buf);
	}

	private void showChildFile(File root, StringBuffer buf) throws FileNotFoundException, IOException {
		logger.info(buf.toString() + root.getName());

		File[] children = root.listFiles();
		for (File child : children) {
			if (child.isDirectory()) {
				showChildFile(child, append(buf));
			} else {
				logger.info(append(buf).toString() + "|" + child.getName());
				FileInputStream fis = new FileInputStream(child);
				BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
				String content = null;
				while ((content = reader.readLine()) != null) {
					content = new String(content.getBytes(), "UTF-8");
					logger.info(content);
				}
			}
		}
	}

	private StringBuffer append(StringBuffer buf) {
		return (new StringBuffer(buf)).append("--");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

	@Override
	public void destroy() {
		basePath = null;
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		String sourcesBasePath = config.getInitParameter(SOURCES_BASE_PATH);
		if (sourcesBasePath != null) {
			basePath = config.getServletContext().getRealPath(sourcesBasePath);
		} else {
			basePath = config.getServletContext().getRealPath(BATH_PATH);
		}
		logger.info("The sources base location is '{}'.", basePath);
	}
}
